<template>
    <div class="cart-container">
        <el-card shadow="never" class="cart-card">
            <!-- 购物车标题 -->
            <div class="cart-header">
                <h2>我的购物车</h2>
                <span class="cart-count">共 {{ totalCount }} 件商品</span>
            </div>

            <!-- 购物车列表 -->
            <div class="cart-list">
                <el-table :data="cartList" style="width: 100%" @selection-change="handleSelectionChange"
                    v-loading="loading" :row-key="row => row.id">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="商品信息" width="400">
                        <template #default="{ row }">
                            <div class="product-info">
                                <img :src="row.goodsImages[0]" class="product-image" />
                                <div class="product-detail">
                                    <div class="product-name">{{ row.goodsTitle }}</div>
                                    <div class="product-spec">{{ row.spec || '默认规格' }}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="单价" width="120">
                        <template #default="{ row }">
                            <span class="product-price">¥{{ row.goodsPrice.toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" width="180">
                        <template #default="{ row }">
                            <el-input-number v-model="row.quantity" :min="1" :max="99"
                                @change="(val) => handleQuantityChange(row, val)" />
                        </template>
                    </el-table-column>
                    <el-table-column label="小计" width="120">
                        <template #default="{ row }">
                            <span class="subtotal">¥{{ (row.goodsPrice * row.quantity).toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                        <template #default="{ row }">
                            <el-button type="text" size="small" @click="handleDelete(row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 购物车底部操作栏 -->
            <div class="cart-footer">
                <div class="cart-actions">
                    <el-checkbox v-model="isAllSelected" @change="handleSelectAllChange">
                        全选
                    </el-checkbox>
                    <el-button type="text" :disabled="selectedItems.length === 0" @click="handleBatchDelete">
                        删除选中
                    </el-button>
                    <el-button type="text" @click="handleClearCart">
                        清空购物车
                    </el-button>
                </div>
                <div class="cart-summary">
                    <div class="summary-item">
                        <span>已选 {{ selectedCount }} 件</span>
                        <span class="total-amount">合计: ¥{{ selectedPrice.toFixed(2) }}</span>
                    </div>
                    <el-button type="primary" size="large" :disabled="selectedItems.length === 0"
                        @click="handleCheckout">
                        去结算({{ selectedCount }})
                    </el-button>
                </div>
            </div>
        </el-card>

        <!-- 猜你喜欢 -->
        <div class="recommend-section">
            <h3 class="recommend-title">猜你喜欢</h3>
            <div class="recommend-list">
                <el-card v-for="item in recommendList" :key="item.id" shadow="hover" class="recommend-item"
                    @click="handleAddToCart(item)">
                    <img :src="item.image" class="recommend-image" />
                    <div class="recommend-info">
                        <div class="recommend-name">{{ item.name }}</div>
                        <div class="recommend-price">¥{{ item.price.toFixed(2) }}</div>
                    </div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

interface CartItem {
    id: number
    goodsId: number
    goodsTitle: string
    goodsImages: string[]
    goodsPrice: number
    quantity: number
    selected: boolean
    spec?: string
}

interface RecommendItem {
    id: number
    name: string
    image: string
    price: number
}

// 购物车假数据
const cartList = ref<CartItem[]>([
    {
        id: 1,
        goodsId: 101,
        goodsTitle: 'Apple iPhone 14 Pro Max',
        goodsImages: [
            'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg',
            'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg'
        ],
        goodsPrice: 9999.00,
        quantity: 1,
        selected: true,
        spec: '256GB 深空黑'
    },
    {
        id: 2,
        goodsId: 102,
        goodsTitle: 'MacBook Pro 14',
        goodsImages: [
            'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg'
        ],
        goodsPrice: 14999.00,
        quantity: 1,
        selected: true,
        spec: 'M2 Pro 16GB 512GB'
    },
    {
        id: 3,
        goodsId: 103,
        goodsTitle: 'AirPods Pro 2',
        goodsImages: [
            'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg'
        ],
        goodsPrice: 1899.00,
        quantity: 2,
        selected: false
    }
])

const loading = ref(false)
const selectedItems = ref<CartItem[]>([])

// 猜你喜欢假数据
const recommendList = ref<RecommendItem[]>([
    {
        id: 4,
        name: 'Apple AirPods Pro 2',
        image: 'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg',
        price: 1899.00
    },
    {
        id: 5,
        name: 'Apple Watch Series 8',
        image: 'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg',
        price: 2999.00
    },
    {
        id: 6,
        name: 'iPad Pro 2022',
        image: 'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg',
        price: 6799.00
    },
    {
        id: 7,
        name: 'MacBook Pro 14',
        image: 'https://img10.360buyimg.com/n1/s450x450_jfs/t1/213540/9/17889/73651/625e2a2aEa9db9a0e/3a13f228d25d1d7a.jpg',
        price: 14999.00
    }
])

// 计算属性
const isAllSelected = computed({
    get: () => cartList.value.length > 0 && cartList.value.every(item => item.selected),
    set: (val) => handleSelectAllChange(val)
})

const totalCount = computed(() => {
    return cartList.value.reduce((total, item) => total + item.quantity, 0)
})

const selectedCount = computed(() => {
    return selectedItems.value.reduce((total, item) => total + item.quantity, 0)
})

const selectedPrice = computed(() => {
    return selectedItems.value.reduce((total, item) => total + (item.goodsPrice * item.quantity), 0)
})

// 方法
const handleSelectionChange = (items: CartItem[]) => {
    selectedItems.value = items
}

const handleQuantityChange = (item: CartItem, newQuantity: number) => {
    item.quantity = newQuantity
    ElMessage.success('修改数量成功')
}

const handleDelete = (item: CartItem) => {
    ElMessageBox.confirm(`确定要删除 ${item.goodsTitle} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        cartList.value = cartList.value.filter(cartItem => cartItem.id !== item.id)
        ElMessage.success('删除成功')
    }).catch(() => {})
}

const handleBatchDelete = () => {
    if (selectedItems.value.length === 0) return

    ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 件商品吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const selectedIds = selectedItems.value.map(item => item.id)
        cartList.value = cartList.value.filter(item => !selectedIds.includes(item.id))
        selectedItems.value = []
        ElMessage.success('批量删除成功')
    }).catch(() => {})
}

const handleClearCart = () => {
    if (cartList.value.length === 0) return

    ElMessageBox.confirm('确定要清空购物车吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        cartList.value = []
        selectedItems.value = []
        ElMessage.success('购物车已清空')
    }).catch(() => {})
}

const handleSelectAllChange = (selected: boolean) => {
    cartList.value.forEach(item => {
        item.selected = selected
    })
    
    if (selected) {
        selectedItems.value = [...cartList.value]
    } else {
        selectedItems.value = []
    }
}

const handleCheckout = () => {
    ElMessageBox.confirm(
        `确定要结算 ${selectedItems.value.length} 件商品吗? 总金额: ¥${selectedPrice.value.toFixed(2)}`,
        '确认订单',
        {
            confirmButtonText: '去支付',
            cancelButtonText: '再想想',
            type: 'success'
        }
    ).then(() => {
        ElMessage.success('正在跳转到支付页面...')
    }).catch(() => {})
}

const handleAddToCart = (item: RecommendItem) => {
    const newItem: CartItem = {
        id: Date.now(),
        goodsId: item.id,
        goodsTitle: item.name,
        goodsImages: [item.image],
        goodsPrice: item.price,
        quantity: 1,
        selected: true
    }
    
    cartList.value.push(newItem)
    selectedItems.value.push(newItem)
    ElMessage.success(`已添加 ${item.name} 到购物车`)
}

// 初始化选中项
onMounted(() => {
    selectedItems.value = cartList.value.filter(item => item.selected)
})
</script>

<style scoped>
.cart-container {
    max-width: 1200px;
    margin: 20px auto;
}

.cart-card {
    border-radius: 8px;
    margin-bottom: 30px;
}

.cart-header {
    display: flex;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
}

.cart-header h2 {
    margin: 0;
    font-size: 20px;
}

.cart-count {
    margin-left: 15px;
    font-size: 14px;
    color: #999;
}

.cart-list {
    padding: 0 20px;
}

.product-info {
    display: flex;
    align-items: center;
}

.product-image {
    width: 80px;
    height: 80px;
    margin-right: 15px;
    object-fit: contain;
}

.product-detail {
    flex: 1;
}

.product-name {
    margin-bottom: 5px;
    font-size: 14px;
}

.product-spec {
    font-size: 12px;
    color: #999;
}

.product-price {
    font-weight: bold;
    color: #f56c6c;
}

.subtotal {
    font-weight: bold;
    color: #f56c6c;
}

.cart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-top: 1px solid #f0f0f0;
}

.cart-actions {
    display: flex;
    align-items: center;
    gap: 15px;
}

.cart-summary {
    display: flex;
    align-items: center;
    gap: 30px;
}

.summary-item {
    display: flex;
    flex-direction: column;
}

.total-amount {
    font-size: 18px;
    font-weight: bold;
    color: #f56c6c;
}

.recommend-section {
    margin-top: 40px;
}

.recommend-title {
    margin-bottom: 20px;
    font-size: 18px;
    color: #333;
}

.recommend-list {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

.recommend-item {
    cursor: pointer;
    transition: all 0.3s;
}

.recommend-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.recommend-image {
    width: 100%;
    height: 180px;
    object-fit: contain;
}

.recommend-info {
    padding: 15px;
}

.recommend-name {
    margin-bottom: 10px;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.recommend-price {
    font-weight: bold;
    color: #f56c6c;
}

@media (max-width: 992px) {
    .recommend-list {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 768px) {
    .recommend-list {
        grid-template-columns: repeat(2, 1fr);
    }

    .cart-footer {
        flex-direction: column;
        gap: 15px;
        align-items: flex-end;
    }
}

@media (max-width: 576px) {
    .recommend-list {
        grid-template-columns: 1fr;
    }

    .product-info {
        flex-direction: column;
        align-items: flex-start;
    }

    .product-image {
        margin-right: 0;
        margin-bottom: 10px;
    }
}

</style>